package com.cdy.store.manager;

import com.cdy.common.uitl.FileUtil;
import io.netty.buffer.ByteBuf;

import java.io.File;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 文件 基于磁盘的管理
 * Created by 陈东一
 * 2019/10/19 0019 15:44
 */
public class FileSystemDisk implements FileSystem {

    // path -> file
    private static final ConcurrentHashMap<String, FileChannel> map = new ConcurrentHashMap<>();
    // 文件根路径
    private static final String path = "d:"+File.separator+"uploadTemp";

    @Override
    public synchronized File findFile(String fileName) throws Exception {
        return FileUtil.openFile(path + File.separator + fileName);
    }

    @Override
    public void writeFile(File file, ByteBuffer byteBuffer, Long begin) throws Exception {
        FileChannel fileChannel = openChannel(file);
        FileUtil.write(fileChannel, byteBuffer, begin);
    }

    @Override
    public FileChannel openChannel(File file) throws Exception {
        FileChannel fileChannel = map.get(file.getPath());
        if (fileChannel == null) {
            synchronized (map) {
                if (fileChannel == null) {
                    fileChannel = FileUtil.openChannel(file);
                    map.put(file.getPath(), fileChannel);
                }
            }
        }
        return fileChannel;
    }

    @Override
    public void closeChannel(File file) throws Exception {
        FileChannel fileChannel = map.remove(file.getPath());
        FileUtil.closeChannel(fileChannel);

    }

    @Override
    public ByteBuf readFile(File file, Long begin, int length) throws Exception {
        FileChannel channel = openChannel(file);
        return FileUtil.readChannel(channel, begin, length);
    }
}
